package com.cy.controller;


import com.cy.annotation.SysLog;
import com.cy.entity.SysConfig;
import com.cy.service.SysConfigService;
import com.cy.service.SysOssService;
import com.cy.utils.R;
import com.cy.utils.RRException;
import com.cy.utils.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


/**
 * Created by 陈熠
 * 2017/8/8.
 */
@Controller
@RequestMapping("/sys/rule")
public class RuleController {
    @Autowired
    private SysOssService sysOssService;
    @Autowired
    private SysConfigService sysConfigService;
    /**
     * 上传文件
     */
    @ResponseBody
    @RequestMapping("/upload/{code}")
    public R upload(@RequestParam("file") MultipartFile file, @PathVariable String code) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        String fileName=file.getOriginalFilename();
        String _extName = fileName.substring(fileName.indexOf("."),fileName.length());//获取扩展名
        if(!".jpg".equals(_extName)&&!".jpeg".equals(_extName)&&!".gif".equals(_extName)&&!".png".equals(_extName)){
            throw new RRException("请上传图片");
        }
        if(file.getSize()>5*1024*1024){
            throw new RRException("图片不能大于5M");
        }
        //上传文件
        String url = UploadUtil.uploadImage(file.getOriginalFilename(),file.getInputStream());
        //保存文件信息
        SysConfig config=new SysConfig();
        config.setCode(code);
        config.setValue(url);
        sysConfigService.setRule(config);
        return R.ok().put("url", url);
    }

    /**
     * 修改金额设置
     */
    @ResponseBody
    @SysLog("修改金额设置")
    @RequestMapping("/money")
    public R money(@RequestBody SysConfig config){
        String value=config.getValue();
        if ("".equals(value)){
            throw new RRException("金额不能为空");
        }
        String regEx = "(^[1-9]([0-9]+)?(\\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\\.[0-9]([0-9])?$)";
        if (!value.matches(regEx)) {
            throw new RRException("请输入正确的金额");
        }
        String code="cfg_money";
        config.setCode(code);
        sysConfigService.setRule(config);
        return R.ok();
    }
    /**
     * 修改分享的链接设置
     */
    @ResponseBody
    @SysLog("修改分享的链接设置")
    @RequestMapping("/share")
    public R share(@RequestBody SysConfig config){
//        String code=config.getCode();
//        config.setCode(code);
        sysConfigService.setRule(config);
        return R.ok();
    }
}
